<template>
  <div class="exercise-list-container">
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <h2 class="title">练习集列表</h2>
            <el-input
              v-model="searchQuery"
              placeholder="搜索练习集..."
              class="search-input"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          <div class="header-right">
            <el-button type="info" @click="fetchExercises" :loading="loading">
              <el-icon><Refresh /></el-icon>刷新列表
            </el-button>
            <el-button type="primary" @click="$router.push('/dashboard/exercises/create')">
              <el-icon><Plus /></el-icon>创建练习集
            </el-button>
            <el-button type="success" @click="$router.push('/dashboard/exercises/simple-create')">
              <el-icon><Plus /></el-icon>快速创建
            </el-button>
          </div>
        </div>
      </template>

      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>

      <div v-else-if="exercises.length === 0" class="empty-state">
        <el-empty description="暂无练习集" :image-size="200">
          <el-button type="primary" @click="$router.push('/dashboard/exercises/create')">
            创建练习集
          </el-button>
        </el-empty>
      </div>

      <div v-else class="exercise-grid">
        <el-card 
          v-for="exercise in paginatedExercises" 
          :key="exercise.id" 
          class="exercise-card"
          shadow="hover"
          @click="viewExerciseDetail(exercise.id)"
        >
          <div class="exercise-card-content">
            <div class="exercise-icon">
              <el-icon><Reading /></el-icon>
            </div>
            <div class="exercise-info">
              <h3 class="exercise-title">{{ exercise.title }}</h3>
              <p class="exercise-description">{{ exercise.description || '暂无描述' }}</p>
              <div class="exercise-meta">
                <span class="meta-item">
                  <el-icon><Document /></el-icon>
                  {{ exercise.question_count || 0 }} 题
                </span>
                <span class="meta-item">
                  <el-icon><User /></el-icon>
                  {{ exercise.author || '未知' }}
                </span>
                <span class="meta-item">
                  <el-icon><Timer /></el-icon>
                  {{ formatDate(exercise.created_at) }}
                </span>
              </div>
            </div>
          </div>
          <div class="exercise-actions">
            <el-button type="primary" size="small" @click.stop="startExercise(exercise.id)">
              开始练习
            </el-button>
            <el-button type="info" size="small" @click.stop="viewExerciseDetail(exercise.id)">
              查看详情
            </el-button>
          </div>
        </el-card>
      </div>

      <el-pagination
        v-if="filteredExercises.length > 0"
        class="pagination"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="filteredExercises.length"
        :page-sizes="[12, 24, 36, 48]"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onActivated, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Search, Plus, Reading, Document, User, Timer, Refresh } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import http from '../utils/axios'

const router = useRouter()
const route = useRoute()
const exercises = ref([])
const loading = ref(true)
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(12)
const lastFetchTime = ref(0)

// 获取练习集列表
const fetchExercises = async () => {
  loading.value = true;
  try {
    const response = await http.get('/exercises/exercise-sets/');
    // 确保exercises.value始终是一个数组
    if (Array.isArray(response.data)) {
      exercises.value = response.data;
    } else if (response.data && Array.isArray(response.data.results)) {
      // 处理分页响应格式
      exercises.value = response.data.results;
    } else {
      console.error('API返回的数据不是数组:', response.data);
      exercises.value = []; // 设置为空数组以避免错误
      ElMessage.warning('获取数据格式异常，请联系管理员');
    }
    lastFetchTime.value = Date.now();
    console.log('练习集列表已更新，共获取', exercises.value.length, '条数据');
  } catch (error) {
    console.error('获取练习集失败:', error);
    ElMessage.error('获取练习集失败，请稍后重试');
    exercises.value = []; // 确保在错误情况下也设置为数组
  } finally {
    loading.value = false;
  }
};

// 过滤练习集
const filteredExercises = computed(() => {
  // 确保exercises.value是数组
  if (!Array.isArray(exercises.value)) {
    console.warn('exercises.value不是数组，返回空数组');
    return [];
  }
  
  if (!searchQuery.value) {
    return exercises.value;
  }
  
  const query = searchQuery.value.toLowerCase();
  return exercises.value.filter(exercise => 
    exercise.title.toLowerCase().includes(query) || 
    (exercise.description && exercise.description.toLowerCase().includes(query))
  );
});

// 计算当前页的练习集
const paginatedExercises = computed(() => {
  // 确保filteredExercises.value是数组
  if (!Array.isArray(filteredExercises.value)) {
    console.warn('filteredExercises.value不是数组，返回空数组');
    return [];
  }
  
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredExercises.value.slice(start, end);
});

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
}

// 页码变化处理
const handlePageChange = (page) => {
  currentPage.value = page;
};

// 每页显示数量变化处理
const handleSizeChange = (size) => {
  pageSize.value = size;
  // 重置到第一页
  currentPage.value = 1;
};

// 查看练习集详情
const viewExerciseDetail = (id) => {
  router.push(`/dashboard/exercises/${id}`)
}

// 开始练习
const startExercise = (id) => {
  router.push(`/dashboard/exercises/${id}/practice`)
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知时间'
  
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 监听路由变化，当返回到此页面时刷新数据
watch(
  () => route.path,
  (newPath) => {
    if (newPath === '/dashboard/exercises') {
      // 如果距离上次获取数据超过10秒，则刷新数据
      const now = Date.now();
      if (now - lastFetchTime.value > 10000) {
        console.log('路由返回到练习集列表，刷新数据');
        fetchExercises();
      }
    }
  }
);

onMounted(() => {
  fetchExercises();
});

// 使用onActivated钩子，在keep-alive组件被激活时调用
onActivated(() => {
  // 如果距离上次获取数据超过10秒，则刷新数据
  const now = Date.now();
  if (now - lastFetchTime.value > 10000) {
    console.log('组件被激活，刷新数据');
    fetchExercises();
  }
});
</script>

<style scoped>
.exercise-list-container {
  padding: 20px;
}

.main-card {
  margin-bottom: 20px;
  background-color: rgba(255, 255, 255, 0.05);
  border: none;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.title {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 600;
}

.search-input {
  width: 300px;
}

.loading-container {
  padding: 20px;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

.exercise-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.exercise-card {
  cursor: pointer;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  background-color: rgba(255, 255, 255, 0.05);
  border: none;
}

.exercise-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.exercise-card-content {
  display: flex;
  gap: 15px;
}

.exercise-icon {
  font-size: 2rem;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
  justify-content: center;
}

.exercise-info {
  flex: 1;
}

.exercise-title {
  margin: 0 0 10px 0;
  font-size: 1.2rem;
  font-weight: 600;
}

.exercise-description {
  margin: 0 0 15px 0;
  color: var(--el-text-color-secondary);
  font-size: 0.9rem;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.exercise-meta {
  display: flex;
  gap: 15px;
  font-size: 0.8rem;
  color: var(--el-text-color-secondary);
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.exercise-actions {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .header-left {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .search-input {
    width: 100%;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .header-right {
    width: 100%;
  }
  
  .header-right .el-button {
    width: 100%;
  }
  
  .exercise-grid {
    grid-template-columns: 1fr;
  }
}
</style> 